import 'dart:async';
import 'dart:ui';

import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/acc_order.dart';
import 'package:factoryside/bean/fee_order_entity.dart';
import 'package:factoryside/generated/json/acc_order_helper.dart';
import 'package:factoryside/generated/json/fee_order_entity_helper.dart';
import 'package:factoryside/home/acc_detail.dart';
import 'package:factoryside/home/fee_apply_detail.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'page_search_order_list.dart';

//配件单、费用单管理
class AccListPage extends StatefulWidget {
  int type = 0; //0配件单 1费用单
  int initialIndex = 0;

  AccListPage(this.type, {this.initialIndex = 0});

  @override
  State<StatefulWidget> createState() {
    return _AccListState();
  }
}

class _AccListState extends State<AccListPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  TabController _tabController;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  List<String> stateTop = ['1', '10', '11', '20', '18'];

  var myTabs;

  List<Widget> pagesTop;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    stateTop = widget.type == 0 ? ['1', '10', '11', '20', '18'] : ['19', '21'];
    initData();
  }

  void initData() {
    this._tabController = TabController(
        initialIndex: widget.initialIndex,
        vsync: this,
        length: stateTop.length);
    pagesTop = stateTop.map((state) {
      return AccListSubPage(widget.type,state);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.type == 0 ? '配件单管理' : '费用单管理'),
          actions: [
            IconButton(
                icon: Image.asset(
                  'assets/search.png',
                  width: 20,
                  height: 20,
                ),
                onPressed: () {
                  push(context, SearchOrderPage());
                })
          ],
        ),
        body: Column(
          children: [
            Container(
              height: 40,
              color: Colors.white,
              child: getTabs(),
            ),
            Expanded(
              child: ExtendedTabBarView(
                controller: _tabController,
                children: pagesTop,
              ),
            ),
          ],
        ));
  }

  TabBar getTabs() {
    myTabs = widget.type == 0
        ? <Tab>[
            Tab(
              text: '待审核',
            ),
            Tab(
              text: '待发件',
            ),
            Tab(
              text: '已发件',
            ),
            Tab(
              text: '已返件待确认',
            ),
            Tab(
              text: '全部',
            ),
          ]
        : [
            Tab(
              text: '待审核',
            ),
            Tab(
              text: '全部',
            ),
          ];
    return buildTabBar();
  }

  TabBar buildTabBar() {
    return TabBar(
      controller: _tabController,
      isScrollable: widget.type==0,
      unselectedLabelColor: Colors.black, //设置未选中时的字体颜色，tabs里面的字体样式优先级最高
      unselectedLabelStyle:
          TextStyle(fontSize: 15), //设置未选中时的字体样式，tabs里面的字体样式优先级最高
      labelColor:
          ColorsUtil.hexToColor('#2456ED'), //设置选中时的字体颜色，tabs里面的字体样式优先级最高
      labelPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      labelStyle: TextStyle(
          fontSize: 15.0,
          fontWeight: FontWeight.bold), //设置选中时的字体样式，tabs里面的字体样式优先级最高
      indicatorColor: ColorsUtil.hexToColor('#2456ED'), //选中下划线的颜色
      indicatorPadding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      indicatorSize:
          TabBarIndicatorSize.label, //选中下划线的长度，label时跟文字内容长度一样，tab时跟一个Tab的长度一样
      indicatorWeight: 2.0, //选中下划线的高度，值越大高度越高，默认为2。0
//                indicator: BoxDecoration(),//用于设定选中状态下的展示样式
      tabs: myTabs,
    );
  }
}

class AccListSubPage extends StatefulWidget {
  int type;
  String state;

  AccListSubPage(this.type,this.state);

  @override
  State createState() => new AccListSubPageState();
}

class AccListSubPageState extends State<AccListSubPage> {
  List items = [];

  var page = 1;
  var limit = 10;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void dispose() {
    // TODO: implement dispose
    _refreshController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    page = 1;
    _fetchData();
  }

  void _fetchData() {
    RequestUtil.post(Api.newFactoryGetOrderList,
        {'State': widget.state, 'page': page, 'limit': limit}).then((value) {
      List list = value['Data']['data'];
      List tempList = [];
      list.forEach((element) {
        tempList.add(widget.type==0?accOrderDataDataFromJson(AccOrderDataData(), element):feeOrderEntityFromJson(FeeOrderEntity(), element));
      });
      if (page == 1) {
        items = tempList;
        _refreshController.resetNoData();
      } else {
        if (tempList.length == 0) {
          _refreshController.loadNoData();
        } else {
          items.addAll(tempList);
        }
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    _fetchData();
    _refreshController.resetNoData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(microseconds: 1000));
    page++;
    _fetchData();
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: ColorsUtil.hexToColor('#F2F2F2'),
      child: items.length == 0
          ? buildSmartRefresher(buildEmptyContainer())
          : buildSmartRefresher(ListView.builder(
              itemBuilder: (BuildContext context, int a) {
                var order = items[a];
                return GestureDetector(
                  child: Card(
                      elevation: 0.0,
                      margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
//            mainAxisAlignment: ,
                          children: [
                            //工单号
                            InkWell(
                              onTap: () {
                                String copyText = widget.type==0?'工单号：${order.orderNumber}':'费用单号：${order.feeNumber}';
                                //复制
                                Clipboard.setData(
                                    ClipboardData(text: copyText));
                                showToast('复制成功');
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 2),
                                decoration: BoxDecoration(
                                    color: ColorsUtil.hexToColor('#D5D4D4'),
                                    borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(5),
                                        topRight: Radius.circular(5))),
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        widget.type==0?'工单号：${order.orderNumber}':'费用单号：${order.feeNumber}',
                                        style: TextStyle(fontSize: 14),
                                      ),
                                    ),
                                    Image.asset(
                                      'assets/copy.png',
                                      width: 25,
                                      height: 25,
                                    )
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Wrap(
                                    spacing: 5,
                                    runSpacing: 5,
                                    children: List.generate(
                                        1,
                                        (element) => Container(
                                              padding: EdgeInsets.symmetric(
                                                  vertical: 3, horizontal: 5),
                                              decoration: BoxDecoration(
                                                  color: colors[element],
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(2))),
                                              child: Text(
                                                widget.type==0?'${order.accessoryStateHtml}':'${order.stateTxt}',
                                                style: TextStyle(
                                                    fontSize: 10,
                                                    color: Colors.white),
                                                textAlign: TextAlign.center,
                                              ),
                                            )).toList(),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                      children: [
                                        Expanded(
                                            child: Text(
                                              widget.type==0?'${order.products}':'${order.name}  ${order.applicationAmount}元',
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 16),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ))
                                      ]),
                                  widget.type==0?Column(
                                    children: [
                                      Row(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                          children: [
                                            Expanded(
                                                child: Text(
                                                  '配件单号：${order.accessoryNo}',
                                                  style: TextStyle(
                                                      color: Colors.black54,
                                                      fontSize: 14),
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                ))
                                          ]),
                                      Row(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                          children: [
                                            Expanded(
                                                child: Text(
                                                  '配件名称：${order.fAccessoryName}',
                                                  style: TextStyle(
                                                      color: Colors.black54,
                                                      fontSize: 14),
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                ))
                                          ]),
                                      Row(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                          children: [
                                            Expanded(
                                                child: Text(
                                                  '收件信息：${order.address}',
                                                  style: TextStyle(
                                                      color: Colors.black54,
                                                      fontSize: 14),
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                ))
                                          ]),
                                      SizedBox(
                                        height: 5,
                                      ),
                                    ],
                                  ):SizedBox(),
                                  Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                      children: [
                                        Expanded(
                                            child: Text(
                                          '申请时间：${widget.type==0?order.createTime:order.createDate}',
                                          style: TextStyle(
                                              color: Colors.black54,
                                              fontSize: 14),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ))
                                      ]),

                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                  onTap: () {
                    push(context, widget.type==0?AccDetailPage(order):FeeDetailPage(order));
                  },
                );
              },
              itemCount: items.length,
            )),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: child,
    );
  }

  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无数据',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
